import socket


def send_to_file(new_client_socket, client_addr):
    # 接受客户端发送过来的文件名
    file_name = new_client_socket.recv(1024).decode('utf-8')
    print('客户端(%s)发送过来的文件名是:%s' % (client_addr, file_name))
    # 打开文件,读取数据
    file_content = None
    try:
        f = open(file_name, 'rb')
        file_content = f.read()
        f.close()
    except Exception:
        print('无下载文件')

    # 回送文件数据
    if file_content:
        new_client_socket.send(file_content)


def main():
    # 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定本地信息
    tcp_server_socket.bind(('', 8080))
    # 让默认的套接字由主动变为被动
    tcp_server_socket.listen(128)

    # 等待客户端链接
    new_client_socket, client_addr = tcp_server_socket.accept()

    send_to_file(new_client_socket, client_addr)

    # 关闭套接字
    new_client_socket.close()
    tcp_server_socket.close()


if __name__ == '__main__':
    main()
